<template>
  <div class='login'>
    <div class='form-container'>
      <el-form
          class='login-form'
          ref='ruleFormRef'
          style='max-width: 800px;'
          :model='ruleForm'
          :rules='rules'
          label-width='auto'
          :size='formSize'
          status-icon
      >
        <div class='login-logo'>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="点我返回首页"
              placement="top-start"
          >
          <img :src="logo" alt="登录" @click="router.push('/')" style="cursor: pointer">
          </el-tooltip>
        </div>
        <el-row style='margin: 20px 0'></el-row>
        <el-row style='margin: 30px; display: flex; justify-content: center'>
          <el-form-item prop='username'>
            <el-input
                type='text'
                v-model='ruleForm.username'
                style='width: 300px'
                placeholder='请输入用户名'
            />
          </el-form-item>
        </el-row>
        <el-row style='margin: 30px; display: flex; justify-content: center'>
          <el-form-item prop='password'>
            <el-input
                type='password'
                v-model='ruleForm.password'
                style='width: 300px'
                placeholder='请输入密码'
            />
          </el-form-item>
        </el-row>
        <el-row style='margin-top: 20px; display: flex; justify-content: center'>
          <el-form-item style='text-align: center'>
            <el-button
                style='text-align: center; width: 300px'
                type='primary'
                size='large'
                @click='submitForm(ruleFormRef)'
            >登录
            </el-button>
          </el-form-item>
        </el-row>
        <el-row>
          <div class="register">
            <a class="container" href="/register">注册</a>
<!--            <el-divider direction="vertical" border-style="dashed" />-->
<!--            <div style='cursor: pointer' @click="router.push('forgetPassword')">忘记密码</div>-->
          </div>
        </el-row>
      </el-form>
    </div>
  </div>

  <Verify
      @success='doLogin'
      :mode="'pop'"
      :captchaType="'blockPuzzle'"
      :imgSize="{ width: '330px', height: '155px' }"
      ref='verify'
  ></Verify>
</template>
<script setup lang='ts'>
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import {Microphone, Plus, Iphone, Search} from '@element-plus/icons'
import Verify from '@/components/verifition/Verify.vue'
import { login,me } from '@/api/login'
import { useUserStore } from '@/stores/user'
import { Message } from '@element-plus/icons-vue'
import { useDefaultStore } from '@/stores/default'
import logoImg from '@/assets/logo.png'
import storage from '@/utils/storage'
import {Base64} from 'js-base64'
import i18n from '@/lang'

interface RuleForm {
  username: string
  password: string
  captchaVO: object
}
const logo = ref(logoImg)
const formSize = ref('default')

const ruleFormRef = ref<FormInstance>()

const router = useRouter()
const route = useRoute()

const ruleForm = reactive<RuleForm>({
  username: '',
  password: '',
  captchaVO: {}
})

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: i18n.global.t('login.userNamePlaceHolder'), trigger: 'blur' }],
  password: [
    {
      required: true,
      message: i18n.global.t('login.passwordPlaceHolder'),
      trigger: 'blur'
    }
  ]
})

/**
 * 获取验证码
 */
const verify = ref({})
const refreshCaptcha = () => {
  verify.value.show()
}

let isSubmit = false


const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl || !verify || !verify.value || !verify.value.show) {
    return
  }
  formEl.validate((valid: boolean) => {
    if (valid) {
      verify.value.show()
    }
  })
}

const userStore = useUserStore()
const doLogin = (verifyResult: any) => {
  if (isSubmit) {
    return
  }
  ruleForm.captchaVO = verifyResult
  login(ruleForm).then((resp: any) => {
    if(resp.code === '00000'){
      const token = resp.data;
      storage.setItem('accessToken',token);
      me().then((resp)=>{
        storage.setItem('userInfo',JSON.stringify(resp.data));
        if(!storage.getItem('currentRateSymbol')){
          storage.setItem('currentRateSymbol','￥')
        }
        if(!storage.getItem('currentLanguage')){
          storage.setItem('currentLanguage','cn')
        }
        const redirect = route.query.redirect;
        if(redirect){
          // /orderDetail?goodsId=111&skuId=2222
          const fullPath = Base64.decode(redirect);
          const path = fullPath.split('?')[0]
          const queryParams = fullPath.split('?')[1]
          let queryParam = null
          if(queryParams){
            queryParam = {}
            const params = queryParams.split('&')
            params.forEach(val => {
              const key = val.split('=')[0];
              const value = val.split('=')[1]
              queryParam[key] = value
            });
          }
          console.log('queryParam:',queryParam);
          const redirectTarget = {path: path}
          if(queryParam){
            redirectTarget['query'] = queryParam
          }
          router.push(redirectTarget);
        }else{
          router.push('/')
        }
      })
    }
    isSubmit = true
  }).catch((resp) => {
    // ElMessage.error(resp);
  })
}
</script>
<style>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  flex-direction: column;
  background: url("@/assets/banner.jpeg") center center no-repeat;
  background-size: 100% 100%;
}

.login-logo {
  height: 50px;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 5px 0;
}

.login-welcome{
  font-size: 1rem;
  font-weight: 700;
  text-align: center;
  line-height: 80px;
}
/*.form-container{
  height: 800px;
}*/
.login-form {
  /* min-height: 50vh; */
  /* display: flex; */
  /* align-items: member; */
  width: 500px;
  /*height: 30vh;*/
  text-align: center;
  margin: 0 auto;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: rgba(0, 0, 0, 0.2) 0px 12px 28px 0px,
  rgba(0, 0, 0, 0.1) 0px 2px 4px 0px,
  rgba(255, 255, 255, 0.05) 0px 0px 0px 1px inset;
}
.register{
  display: flex;
  text-align: center;
  justify-content: end;
  width: 100%;
  margin-bottom: 10px;
  padding-right: 50px;
}
.register .container{
  height: 1em;
  line-height: 1em;
  cursor: pointer;
  color: #222222;
}
.register .container:hover{
  background-color: #FFFFFF;
}
</style>
